<template>
  <div class="app-container">
    <el-card class="table-container" shadow="never">
      <template #header>
        <el-button v-hasPerm="['sys:menu:add']" type="success" @click="handleOpenDialog(0)">
          <template #icon>
            <i-ep-plus />
          </template>
          新增
        </el-button>
        <el-button v-hasPerm="['sys:menu:query']" type="primary" @click="handleQuery()">
          <template #icon>
            <i-ep-refresh />
          </template>
          刷新
        </el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="menuTableData"
        :indent="20"
        :lazy="true"
        :stripe="true"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
        highlight-current-row
        row-key="id"
        @row-click="handleRowClick"
      >
        <el-table-column label="菜单名称" min-width="100" width="300">
          <template #default="scope">
            <template v-if="scope.row.icon && scope.row.icon.startsWith('el-icon')">
              <el-icon style="vertical-align: -0.15em">
                <component :is="scope.row.icon.replace('el-icon-', '')" />
              </el-icon>
            </template>
            <template v-else-if="scope.row.icon">
              <svg-icon :icon-class="scope.row.icon" />
            </template>
            <template v-else>
              <svg-icon icon-class="menu" />
            </template>
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column label="类型" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.menuType === 'folder'" type="warning"> 目录</el-tag>
            <el-tag v-if="scope.row.menuType === 'menu'" type="success"> 菜单</el-tag>
            <el-tag v-if="scope.row.menuType === 'button'" type="danger"> 按钮</el-tag>
            <el-tag v-if="scope.row.menuType === 'extlink'" type="info"> 外链</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="路由路径" min-width="150" prop="routePath" width="300" />

        <el-table-column label="组件路径" min-width="250" prop="component" width="300" />

        <el-table-column label="权限标识" prop="permissions" width="300" />

        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.enabled" type="success">使用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="可见性" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.visible" type="success">显示</el-tag>
            <el-tag v-else type="info">隐藏</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="排序" prop="orderNum" width="80" />

        <el-table-column fixed="right" label="操作" width="300">
          <template #default="scope">
            <el-button
              v-if="scope.row.type == 'folder' || scope.row.type == 'menu'"
              v-hasPerm="['sys:menu:add']"
              link
              size="small"
              type="primary"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              <i-ep-plus />
              新增
            </el-button>

            <el-button
              v-hasPerm="['sys:menu:edit']"
              link
              size="small"
              type="primary"
              @click.stop="handleOpenDialog(undefined, scope.row.id)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:menu:delete']"
              link
              size="small"
              type="danger"
              @click.stop="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-drawer v-model="dialog.visible" :title="dialog.title" size="50%" @close="handleCloseDialog">
      <el-form ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="父级菜单" prop="pid">
          <el-tree-select
            v-model="formData.pid"
            :data="menuOptions"
            :render-after-expand="false"
            check-strictly
            filterable
            placeholder="选择上级菜单"
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>

        <el-form-item label="菜单类型" prop="menuType">
          <el-radio-group v-model="formData.menuType" @change="handleMenuTypeChange">
            <el-radio value="folder">目录</el-radio>
            <el-radio value="menu">菜单</el-radio>
            <el-radio value="button">按钮</el-radio>
            <el-radio value="extlink">外链</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.menuType == 'extlink'" label="外链地址" prop="routePath">
          <el-input v-model="formData.routePath" placeholder="请输入外链完整路径" />
        </el-form-item>

        <el-form-item v-if="formData.menuType === 'menu'" prop="routeName">
          <template #label>
            <div>
              路由名称
              <el-tooltip effect="light" placement="bottom">
                <template #content>
                  如果需要开启缓存，需保证页面 defineOptions 中的 name 与此处一致，建议使用驼峰。
                </template>
                <i-ep-QuestionFilled class="inline-block" />
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="formData.routeName" placeholder="User" />
        </el-form-item>

        <el-form-item
          v-if="formData.menuType === 'folder' || formData.menuType === 'menu'"
          prop="routePath"
        >
          <template #label>
            <div>
              路由路径
              <el-tooltip effect="light" placement="bottom">
                <template #content>
                  定义应用中不同页面对应的 URL 路径，目录需以 / 开头，菜单项不用。例如：系统管理目录
                  /system，系统管理下的用户管理菜单 user。
                </template>
                <i-ep-QuestionFilled class="inline-block" />
              </el-tooltip>
            </div>
          </template>
          <el-input
            v-if="formData.menuType == 'folder'"
            v-model="formData.routePath"
            placeholder="system"
          />
          <el-input v-else v-model="formData.routePath" placeholder="user" />
        </el-form-item>
        <el-form-item v-if="formData.menuType == 'menu'" prop="component">
          <template #label>
            <div>
              组件路径
              <el-tooltip effect="light" placement="bottom">
                <template #content>
                  组件页面完整路径，相对于 src/views/，如 system/user/index，缺省后缀 .vue
                </template>
                <i-ep-QuestionFilled class="inline-block" />
              </el-tooltip>
            </div>
          </template>

          <el-input v-model="formData.component" placeholder="system/user/index" style="width: 95%">
            <template v-if="formData.menuType == 'menu'" #prepend> src/views/</template>
            <template v-if="formData.menuType == 'menu'" #append> .vue</template>
          </el-input>
        </el-form-item>

        <el-form-item v-if="formData.menuType == 'menu'">
          <template #label>
            <div>
              路由参数
              <el-tooltip effect="light" placement="bottom">
                <template #content>
                  组件页面使用 `useRoute().query.参数名` 获取路由参数值。
                </template>
                <i-ep-QuestionFilled class="inline-block" />
              </el-tooltip>
            </div>
          </template>

          <div v-if="!formData.params || formData.params.length === 0">
            <el-button plain type="success" @click="formData.params = [{ key: '', value: '' }]">
              添加路由参数
            </el-button>
          </div>

          <div v-else>
            <div v-for="(item, index) in formData.params" :key="index">
              <el-input v-model="item.key" placeholder="参数名" style="width: 100px" />

              <span class="mx-1">=</span>

              <el-input v-model="item.value" placeholder="参数值" style="width: 100px" />

              <el-icon
                v-if="formData.params.indexOf(item) === formData.params.length - 1"
                class="ml-2 cursor-pointer color-[var(--el-color-success)]"
                style="vertical-align: -0.15em"
                @click="formData.params.push({ key: '', value: '' })"
              >
                <CirclePlusFilled />
              </el-icon>
              <el-icon
                class="ml-2 cursor-pointer color-[var(--el-color-danger)]"
                style="vertical-align: -0.15em"
                @click="formData.params.splice(formData.params.indexOf(item), 1)"
              >
                <DeleteFilled />
              </el-icon>
            </div>
          </div>
        </el-form-item>

        <el-form-item v-if="formData.menuType !== 'button'" label="显示状态" prop="visible">
          <el-radio-group v-model="formData.visible">
            <el-radio :value="true">显示</el-radio>
            <el-radio :value="false">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.menuType === 'folder' || formData.menuType === 'menu'">
          <template #label>
            <div>
              始终显示
              <el-tooltip effect="light" placement="bottom">
                <template #content>
                  选择“是”，即使目录或菜单下只有一个子节点，也会显示父节点。
                  <br />
                  选择“否”，如果目录或菜单下只有一个子节点，则只显示该子节点，隐藏父节点。
                  <br />
                  如果是叶子节点，请选择“否”。
                </template>
                <i-ep-QuestionFilled class="inline-block" />
              </el-tooltip>
            </div>
          </template>
          <el-radio-group v-model="formData.alwaysShow">
            <el-radio :value="true">是</el-radio>
            <el-radio :value="false">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.menuType === 'menu'" label="页面缓存">
          <el-radio-group v-model="formData.keepAlive">
            <el-radio :value="true">开启</el-radio>
            <el-radio :value="false">关闭</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.orderNum"
            :min="0"
            controls-position="right"
            style="width: 100px"
          />
        </el-form-item>

        <!-- 权限标识 -->
        <el-form-item v-if="formData.menuType == 'button'" label="权限标识" prop="perm">
          <el-input v-model="formData.permissions" placeholder="sys:user:add" />
        </el-form-item>

        <el-form-item v-if="formData.menuType !== 'button'" label="图标" prop="icon">
          <!-- 图标选择器 -->
          <icon-select v-model="formData.icon" />
        </el-form-item>

        <el-form-item v-if="formData.menuType == 'folder'" label="跳转路由">
          <el-input v-model="formData.redirect" placeholder="跳转路由" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import request from '@/utils/request'

defineOptions({
  name: 'PlatformMenu',
  inheritAttrs: false
})
const menuOptions = ref([])
const menuFormRef = ref(ElForm)

const BASE_URL = '/api/yyplatform/admin/sys/menu/'

const dialog = reactive({
  title: '新增菜单',
  visible: false
})

// 初始菜单表单数据
const initialMenuFormData = ref({
  routePath: '',
  routeName: '',
  menuType: '',
  name: '',
  permissions: '',
  orderNum: 0,
  visible: false,
  remark: '',
  component: 'Layout',
  enabled: true,
  icon: '',
  keepAlive: false,
  alwaysShow: false,
  redirect: false,
  id: 0
})

// 菜单表单数据
const formData = ref({ ...initialMenuFormData.value })
// 表单验证规则
const rules = reactive({
  parentId: [{ required: true, message: '请选择顶级菜单', trigger: 'blur' }],
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择菜单类型', trigger: 'blur' }],
  routeName: [{ required: true, message: '请输入路由名称', trigger: 'blur' }],
  routePath: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
  component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
  visible: [{ required: true, message: '请输入路由路径', trigger: 'blur' }]
})

const loading = ref(false)
const menuTableData = ref([])

function handleRowClick(row) {
  console.log('click row', row)
}

function submitForm() {
  menuFormRef.value.validate(async (isValid) => {
    if (isValid) {
      const menuId = formData.value.id
      if (menuId) {
        let updateRes = await request({
          url: `${BASE_URL}/update`,
          method: 'post',
          data: formData.value
        })

        ElMessage.success('修改成功')
        handleCloseDialog()
        await handleQuery()
      } else {
        let addRes = await request({
          url: `${BASE_URL}/save`,
          method: 'post',
          data: formData.value
        })
        ElMessage.success('新增成功')
        handleCloseDialog()
        await handleQuery()
      }
    }
  })
}

function handleCloseDialog() {
  dialog.visible = false
}

function handleMenuTypeChange(type) {
  formData.value.menuType = type
}

async function handleOpenDialog(pid, id) {
  let rootRes = await request({
    url: `${BASE_URL}/options`,
    method: 'get',
    params: {
      onlyRoot: true
    }
  })
  menuOptions.value = [{ value: 0, label: '顶级菜单', children: rootRes.data }]

  dialog.visible = true
  if (id) {
    dialog.title = '编辑菜单'

    let updateRes = await request({
      url: `${BASE_URL}/get?id=${id}`,
      method: 'get'
    })
    formData.value = updateRes
  } else {
    dialog.title = '新增菜单'
    formData.value = {
      ...initialMenuFormData.value
    }
  }
}

async function handleDelete(id) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let res = await request({
      url: `${BASE_URL}/delete`,
      method: 'post',
      data: {
        id: id
      },
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    await handleQuery()
  })
}

// 查询菜单
async function handleQuery() {
  loading.value = true
  let res = await request({
    url: `${BASE_URL}/query`,
    method: 'get'
  })
  menuTableData.value = res
  loading.value = false
}

onMounted(() => {
  handleQuery()
})
</script>
